package pe.gob.mtpe.construcsys.utils;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;



public class StringLimiterConverter implements Converter {
private static final String LIMIT_PARAMETER_NAME = "limit";
private static final int DEFAULT_LIMIT = 20;

@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
return limit(value, getLimitAttribute(component));
}

@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (! (value instanceof String))
return null;
else {
return limit(value.toString(), getLimitAttribute(component));
}
}

private int getLimitAttribute(UIComponent component) {
Object att = component.getAttributes().get(LIMIT_PARAMETER_NAME);
if (att == null)
return DEFAULT_LIMIT;
else
return Integer.parseInt((String)component.getAttributes().get(LIMIT_PARAMETER_NAME));
}

private String limit(String s, int limit) {
/*String limited = s;
String limited2 = s;*/
String cadena = s;
String cadena2 ="";
String[] arCadena=s.split(" ");

for(int i=1;i<arCadena.length+1;i++){
	if(arCadena.length==1){
		cadena2=arCadena[0];
	}else{
		if(i%2==0){
			cadena2=cadena2+" "+arCadena[i-1]+"<br/>";
		}else{
			cadena2=cadena2+" "+arCadena[i-1];
		}
	}
}
if(arCadena.length==0){
	cadena2=cadena;
}
/*if (! (s.length() <= limit)){
	 
	Integer tam2=s.length();
	do{
		
			System.out.println("1");
			limited2 = limited.substring(0, limit);
			limited=limited.substring(limit+1,limited.length());
			cadena=cadena+limited2+"<br/>";
			tam2=limited.length();
		
		System.out.println("2"+cadena);
	}while(!(tam2<=limit));
	System.out.println("3 "+cadena);
		
	
}*/

return cadena2.trim();
}


}